package cn.bonoon.kernel.web.components;

import static cn.bonoon.kernel.util.StringHelper.isEmpty;
import cn.bonoon.kernel.descriptors.UIPropertyAccessor;
import cn.bonoon.kernel.web.annotations.components.AsCheckbox;
import cn.bonoon.kernel.web.annotations.components.SelectorOption;
import cn.bonoon.kernel.web.html.UIPropertyBuilder;
import cn.bonoon.kernel.web.html.form.ComponentPropertyParser;

public class CheckboxComponent extends AbstractComponent {
	private final SelectorOption[] options;
	private final int column;
	private final String name;
	public CheckboxComponent(ComponentPropertyParser property, UIPropertyAccessor accessor, AsCheckbox asCheckbox) {
		super(property, accessor);
		this.options = asCheckbox.options();
		this.column = asCheckbox.column();
		this.name = asCheckbox.value();
	}
	public CheckboxComponent(ComponentPropertyParser property, UIPropertyAccessor accessor, String name) {
		super(property, accessor);
		this.options = null;
		this.column = 0;
		this.name = name;
	}

	@Override
	protected void parser(UIPropertyBuilder builder) {
		StringBuilder html = builder.getInitHtml();
		
		if (null != options && options.length > 0) {
			int len = options.length;
			html.append("<table border='0' cellspacing='0' cellpadding='0' style='padding:0;margin:0;'><tr>");
			int l = 0;
			for (int i = 0; i < len; i++) {
				SelectorOption opt = options[i];
				String v = opt.value(), n = opt.name();
				if (isEmpty(v)){
					v = Integer.toString(i);
				}else if (isEmpty(n)){
					n = v;
				}
				String checkboxId = componentId + '-' + i;
				html.append("<td align='left'><input type='checkbox' name='").append(componentName);
				html.append("' style='vertical-align:middle' id='").append(checkboxId);
				html.append("' value='").append(v);
				html.append("' #if($").append(builder.getBindedName());
				html.append('.').append(componentName);
				html.append(".contains('").append(v);
				html.append("')checked='checked'#end><label for='").append(checkboxId);
				html.append("'>").append(n).append("</label></td>");
				if (column > 0) {
					if (l < column) {
						l++;
					} else {
						l = 0;
						html.append("</tr><tr>");
					}
				}
			}
			html.append("</tr></table>");
		} else {
			html.append("<input style='vertical-align:middle;margin-top:-2px; margin-bottom:1px;'");
			__component(html);
			html.append(" type='checkbox' value='true' #if($").append(builder.getBindedName());
			html.append('.').append(componentName);
			if(!accessor.isBoolean()){
				html.append(" == \"true\"");
			}
			html.append(")checked='checked'#end/><label for='").append(componentId);
			html.append("'>").append(name).append("</label>");
		}
	}
}
